Page({
  data: {
    dormInfo: {
      building: '兰园',
      buildingNum: '3',
      roomNum: '501'
    },
    weatherNotice: '',
    utilityBill: {
      total: 85.60,
      recommendation: ''
    },
    loadingUtilityAnalysis: false,
    repairDescription: '',
    repairAnalysis: '',
    loadingRepairAnalysis: false,
    announcements: [
      { id: 1, title: '关于宿舍安全用电的通知', time: '昨天' },
      { id: 2, title: '期末宿舍卫生检查安排', time: '3天前' }
    ],
    useZhipuAI: true,
    apiFailedCount: 0
  },

  onLoad: function() {
    this.loadDormInfo();
    this.getWeatherNotice();
    this.analyzeUtilityBill();
  },
  
  loadDormInfo: function() {
    // 未来可以从API获取实际宿舍信息
  },
  
  handleQuickAction: function(e) {
    var action = e.currentTarget.dataset.action;
    
    switch(action) {
      case 'repair':
        wx.createSelectorQuery().select('.repair-input').boundingClientRect(function(rect){
          wx.pageScrollTo({
            scrollTop: rect.top,
            duration: 300
          });
        }).exec();
        break;
      case 'bill':
        this.viewUtilityDetails();
        break;
      case 'schedule':
        wx.showToast({
          title: '值日表功能开发中',
          icon: 'none'
        });
        break;
      case 'visitor':
        wx.showToast({
          title: '访客登记功能开发中',
          icon: 'none'
        });
        break;
    }
  },
  
  getWeatherNotice: function() {
    var userPrompt = "你是宿舍管理AI助手。请根据当前季节和天气情况，生成一条关于宿舍生活的提醒或建议。当前是" + 
      new Date().getMonth() + "月" + new Date().getDate() + "日。回复必须简短、实用且只包含提醒内容本身，不要有任何多余文字。";
    
    this.callAIAPI(
      [{ role: 'user', content: userPrompt }],
      null,
      this.handleWeatherNoticeResponse.bind(this),
      function(error) {
        console.error('获取天气提醒失败:', error);
      },
      null,
      'weather'
    );
  },
  
  handleWeatherNoticeResponse: function(response) {
    var notice = response.replace(/["""'']/g, '').trim();
    this.setData({ weatherNotice: notice });
  },
  
  analyzeUtilityBill: function() {
    var total = this.data.utilityBill.total;
    var userPrompt = "作为宿舍管理AI助手，请根据本月宿舍水电费总额" + total + "元，计算4人宿舍的人均分摊金额。" +
      "考虑到宿舍成员可能有不同的用电习惯，给出一个公平合理的分摊方案。" +
      "回复格式要求：只需回复一句话'根据历史用量和人数，建议每人分摊 ￥ XX.XX。'，不要有任何解释或多余内容。";
    
    this.setData({ loadingUtilityAnalysis: true });
    
    this.callAIAPI(
      [{ role: 'user', content: userPrompt }],
      'loadingUtilityAnalysis',
      this.handleUtilityAnalysisResponse.bind(this),
      function(error) {
        console.error('水电费分析失败:', error);
      },
      null,
      'utility'
    );
  },
  
  handleUtilityAnalysisResponse: function(response) {
    this.setData({
      'utilityBill.recommendation': response,
      loadingUtilityAnalysis: false
    });
  },
  
  viewUtilityDetails: function() {
    wx.showToast({
      title: '水电费详情页开发中',
      icon: 'none'
    });
  },
  
  onRepairInputChange: function(e) {
    this.setData({ repairDescription: e.detail.value });
  },
  
  submitRepair: function() {
    if (!this.data.repairDescription) {
      wx.showToast({
        title: '请描述您的问题',
        icon: 'none'
      });
      return;
    }
    
    var description = this.data.repairDescription;
    var promptPrefix = "作为宿舍管理AI助手，请分析以下报修问题，并分配合适的维修类型和紧急程度。问题描述：";
    var promptMiddle = "。请分析这属于什么类型的问题（如水电维修、家具损坏等），评估紧急程度，并给出处理建议。";
    var promptSuffix = "回复格式要求：\"检测到问题为XXX，已通知XXX维修师傅。\" 不要有任何解释或多余内容。";
    
    var userPrompt = promptPrefix + description + promptMiddle + promptSuffix;
    
    this.setData({ loadingRepairAnalysis: true });
    
    this.callAIAPI(
      [{ role: 'user', content: userPrompt }],
      'loadingRepairAnalysis',
      this.handleRepairAnalysisResponse.bind(this),
      function(error) {
        console.error('报修分析失败:', error);
        this.setData({ loadingRepairAnalysis: false });
      }.bind(this),
      null,
      'repair'
    );
  },
  
  handleRepairAnalysisResponse: function(response) {
    this.setData({
      repairAnalysis: response,
      loadingRepairAnalysis: false
    });
    
    wx.showToast({
      title: '报修提交成功',
      icon: 'success'
    });
  },
  
  viewMoreAnnouncements: function() {
    wx.showToast({
      title: '公告列表页开发中',
      icon: 'none'
    });
  },
  
  callAIAPI: function(messages, loadingFlag, onSuccess, onError, resultField, mockDataType) {
    if (resultField === undefined) resultField = null;
    if (mockDataType === undefined) mockDataType = 'default';
    
    if (loadingFlag) {
      var dataObj = {};
      dataObj[loadingFlag] = true;
      this.setData(dataObj);
    }
    
    if (resultField) {
      var clearObj = {};
      clearObj[resultField] = '';
      this.setData(clearObj);
    }

    var zhipuAI = require('../../utils/zhipu_ai');
    
    if (this.data.useZhipuAI) {
      var self = this;
      zhipuAI.callZhipuAPI(messages, {
        model: 'glm-4-air-250414',
        fallbackToMock: true,
        mockType: mockDataType,
        onSuccess: function(aiResponse, fullResponse) {
          console.log('智谱AI响应成功:', aiResponse);
          
          if (fullResponse && fullResponse.mock) {
            wx.showToast({
              title: '使用模拟数据返回结果',
              icon: 'none',
              duration: 2000
            });
          } else {
            var resetObj = {apiFailedCount: 0};
            self.setData(resetObj);
          }
          
          if (resultField) {
            var resultObj = {};
            resultObj[resultField] = aiResponse;
            self.setData(resultObj);
          }
          
          if (onSuccess) onSuccess(aiResponse);
        },
        onError: function(errorMsg, errorData) {
          console.error('智谱AI响应错误:', errorMsg, errorData);
          
          var newFailCount = self.data.apiFailedCount + 1;
          var countObj = {apiFailedCount: newFailCount};
          self.setData(countObj);
          
          if (newFailCount >= 3) {
            wx.showToast({
              title: '已自动切换到模拟数据模式',
              icon: 'none',
              duration: 2000
            });
            
            var mockResult = zhipuAI.getMockData(mockDataType);
            if (resultField) {
              var mockObj = {};
              mockObj[resultField] = mockResult;
              self.setData(mockObj);
            }
            if (onSuccess) onSuccess(mockResult);
          } else {
            if (errorMsg.includes('429') || errorMsg.includes('401')) {
              var toastMsg = errorMsg.includes('429') 
                ? '今日API调用次数已超限，使用模拟数据'
                : 'API认证失败，使用模拟数据';
              
              wx.showToast({
                title: toastMsg,
                icon: 'none',
                duration: 3000
              });
              
              var mockResult = zhipuAI.getMockData(mockDataType);
              if (resultField) {
                var mockObj = {};
                mockObj[resultField] = mockResult;
                self.setData(mockObj);
              }
              if (onSuccess) onSuccess(mockResult);
            } else {
              if (resultField) {
                var errObj = {};
                errObj[resultField] = 'AI服务暂时不可用: ' + errorMsg;
                self.setData(errObj);
              }
              if (onError) onError(errorMsg);
            }
          }
        },
        onComplete: function() {
          if (loadingFlag) {
            var completeObj = {};
            completeObj[loadingFlag] = false;
            self.setData(completeObj);
          }
        }
      }).catch(function(err) {
        console.error('AI API调用异常:', err);
        if (loadingFlag) {
          var errorObj = {};
          errorObj[loadingFlag] = false;
          self.setData(errorObj);
        }
      });
    } else {
      var self = this;
      setTimeout(function() {
        var zhipuAI = require('../../utils/zhipu_ai');
        var mockResult = zhipuAI.getMockData(mockDataType);
        
        if (resultField) {
          var resultObj = {};
          resultObj[resultField] = mockResult;
          self.setData(resultObj);
        }
        
        if (onSuccess) onSuccess(mockResult);
        
        if (loadingFlag) {
          var loadingObj = {};
          loadingObj[loadingFlag] = false;
          self.setData(loadingObj);
        }
        
        wx.showToast({
          title: '已使用模拟数据，API调用已关闭',
          icon: 'none'
        });
      }, 1000);
    }
  }
})